package org.geektimes.projects.user.web.listener;

import org.geektimes.projects.jmx.custom.UserManager;
import org.geektimes.projects.user.domain.User;

import javax.management.MBeanServer;
import javax.management.MBeanServerFactory;
import javax.management.ObjectName;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.lang.management.ManagementFactory;

/**
 * @author biwin
 */
public class JMXInitializerListener implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
        try {
            mBeanServer.registerMBean(createUserMBean(new User()), new ObjectName(
                    "org.geektimes.projects.user.domain.Use:type=UserManager"));
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {

    }

    private Object createUserMBean(User user) {
        return new UserManager(user);
    }
}

